#include<debuglog.h>
#include<QCoreApplication>
#include<QFile>
#include<QIODevice>
#include<QTextStream>
#include<QDateTime>
#include<QMutex>

DebugLog::DebugLog(QObject *parent)
{
    path = "log.txt";
}

void DebugLog::writelog(QString txt)
{
    static QMutex mutex;
    mutex.lock();

    QString dir = QCoreApplication::applicationDirPath();
    dir = dir + "/" + path;
    QFile file(dir);
    if(file.open(QIODevice::WriteOnly | QIODevice::Append))
    {
        QTextStream stream(&file);

        QDateTime time = QDateTime::currentDateTime();
        QString timestr = time.toString("yyyy.MM.dd hh:mm:ss.zzz");
        stream << "[" + timestr + "] " << txt << endl;
    }
    file.close();

    mutex.unlock();
}

void DebugLog::infoLog(QString txt)
{
    static QMutex mutex;
    mutex.lock();

    QString dir = QCoreApplication::applicationDirPath();
    dir = dir + "/" + path;
    QFile file(dir);
    if(file.open(QIODevice::WriteOnly | QIODevice::Append))
    {
        QTextStream stream(&file);

        QDateTime time = QDateTime::currentDateTime();
        QString timestr = time.toString("yyyy.MM.dd hh:mm:ss.zzz");
        stream << "[" + timestr + "] info:" << txt << endl;
    }
    file.close();

    mutex.unlock();
}

void DebugLog::errLog(QString txt)
{
    static QMutex mutex;
    mutex.lock();

    QString dir = QCoreApplication::applicationDirPath();
    dir = dir + "/" + path;
    QFile file(dir);
    if(file.open(QIODevice::WriteOnly | QIODevice::Append))
    {
        QTextStream stream(&file);

        QDateTime time = QDateTime::currentDateTime();
        QString timestr = time.toString("yyyy.MM.dd hh:mm:ss.zzz");
        stream << "[" + timestr + "] error:" << txt << endl;
    }
    file.close();

    mutex.unlock();
}

void DebugLog::warnLog(QString txt)
{
    static QMutex mutex;
    mutex.lock();

    QString dir = QCoreApplication::applicationDirPath();
    dir = dir + "/" + path;
    QFile file(dir);
    if(file.open(QIODevice::WriteOnly | QIODevice::Append))
    {
        QTextStream stream(&file);

        QDateTime time = QDateTime::currentDateTime();
        QString timestr = time.toString("yyyy.MM.dd hh:mm:ss.zzz");
        stream << "[" + timestr + "] warning:" << txt << endl;
    }
    file.close();

    mutex.unlock();
}
